<?php
/**
 * 系统日志管理
 */
class DebugLogApp extends CommonApp{
	
	private $logDirArr = null;
	private $logDir = null;
	
	public function __construct() {
		$this->logDir = dirname(LOG_DIR);
		$this->logDirArr = $this->getLogDir();
	}
	
	/**
	 * 获得日志目录
	 */
	private function getLogDir(){
		if(!is_dir($this->logDir)) return false;
		$dirObj = opendir($this->logDir);
		while($file = readdir($dirObj)){
			if($file!='.' && $file!='..' && is_dir($this->logDir.'/'.$file)){
				$logDirArr[$file] = $file;
			}
		}
		return $logDirArr;
	}
	
	public function indexAct(){
		$where = '1 ';
		if(My::is_date(My::arr2var($_GET,'create_time')))
			$where .= "AND `create_time` like '".I('get.create_time')."%' ";
		if(My::arr2var($_GET,'app_name')!='')
			$where .= "AND `app_name`='".I('get.app_name')."' ";
		$page = My::page(DB('debug_log')->where($where)->count());
		$list = DB('debug_log')->where($where)->order("create_time DESC")->limit($page['limits'])->select();
		$this->assign('apps',$this->logDirArr);
		$this->assign('list', $list);
		$this->assign('page', $page);
		$this->assign('sqlLog', S('SqlLog'));
		$this->display();
	}
	
	/**
	 * 获得设置
	 */
	private function getSet(){
		$set = '<settings>
			  <start_on_axis>0</start_on_axis>
			  <plot_area>
				<border_alpha>100</border_alpha>
				<margins>
				  <left>50</left>
				  <right>25</right>
				  <top>50</top>
				</margins>
			  </plot_area>
			  <axes>
				<x>
				  <tick_length>5</tick_length>
				  <width>1</width>
				</x>
				<y_left>
				  <tick_length>5</tick_length>
				  <width>1</width>
				  <type>stacked</type>
				</y_left>
			  </axes>
			  <labels>
				<label lid="0">
				  <text><![CDATA[<b>系统日志统计报表</b>]]></text>
				  <y>20</y>
				  <align>center</align>
				</label>
			  </labels>
			</settings>';
		exit($set);
	}
	
	/**
	 * 获得数据
	 */
	private function getXMLData(){
		$colors = array('#FF9E01','#0D8ECF','#64004B','#489620','#FCD202');
		$num = 0;
		$graph = $series = null;
		foreach($this->logDirArr as $appName){
			$graph .= '<graph title="'.$appName.'" line_width="2" bullet="round" color="'.$colors[$num].'">';
			for($i=14;$i>=0;$i--){
				$date = date('Y-m-d',strtotime("-$i DAY"));
				if($num == 0){
					$series .= "<value xid='{$i}'>{$date}</value>";
				}
				$count = DB('debug_log')->where("DATE_FORMAT(create_time,'%Y-%m-%d')='{$date}' AND app_name='{$appName}'")->count();
				$graph .= "<value xid='{$i}'>$count</value>";
			}
			$graph .= '</graph>';
			$num++;
		}
		
		$data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><chart><series>{$series}</series><graphs>{$graph}</graphs></chart>";
		exit($data);
	}
	
	/**
	 * 导入日志
	 */
	public function importAct(){
		$apps = $this->logDirArr;
		$count = 0;
		if(is_array($apps)){
			foreach($apps as $appName){
				$logDirName = "{$this->logDir}/{$appName}/debug/";
				if(!is_dir($logDirName)){
					continue;
				}
				$openDir = opendir($logDirName);
				while($file = readdir($openDir)){
					if($file == '.' || $file == '..'){
						continue;
					}
					// 正式导入日志数据
					$logFile = "{$logDirName}{$file}/{$file}.log";
					if(file_exists($logFile)){
						$files = file($logFile);
						if(is_array($files)){
						    $content = '';
							foreach($files as $val){
							    $content .= $val;
							    $line_str = trim($val);
							    if(!empty($line_str)){
							        continue;
							    }
								$dataArr = My::explode("\r\n",$content);
								$content = '';
								if (count($dataArr)<4)
								    continue;
								if($dataArr[1] == $dataArr[2])
								    $dataArr[2] = $dataArr[3];
									
								//时间与访问链接
								preg_match_all("/(?:\[)(.*)(?:\])/i",$dataArr[0], $create_time); 
								$data['create_time'] = date('Y-m-d H:i:s',strtotime(My::arr2var($create_time,'1.0')));
								$data['url'] = trim(str_replace(My::arr2var($create_time,'0.0'),"",$dataArr[0]));
								//错误级别与信息
								preg_match('/([^:]+?):\s/i',$dataArr[1],$err);
								$data['level_name'] = My::arr2var($err,'1');
								$data['msg'] = trim(str_replace(My::arr2var($err,'0'),"",$dataArr[1]));
								//文件与行数
								preg_match_all("/(?:\第\s*)(\d+)(?:\s*\行\.?)/i",$dataArr[2], $line);
								$data['line_number'] = My::arr2var($line,'1.0');
								$data['file_path'] = trim(str_replace(My::arr2var($line,'0.0'),"",$dataArr[2]));
								//app
								$data['app_name'] = $appName;
	
								if((DB('debug_log')->add($data)) > 0){
									$count++;
								}
								$content = '';
							}
						}
						rename($logFile, $logFile.date('YmdHis').'.bak');
					}
					
				}
			}
		}
		$this->ajaxReturn(200, "已成功增加 {$count} 条日志！");
	}
 
	/**
	 * 设置是否开启数据库记录
	 */
	public function setSqlLogAct(){
	    $value = I('request.value');
	    if(!in_array($value,array('0','1')))
	        $this->ajaxReturn(300, '参数无效');
	        //把是否开启数据库记录的状态写入缓存
	        S('SqlLog',$value);
	}
}